import 'dart:convert';

import 'package:codemode/utils/MyLoadingDialog.dart';
import 'package:codemode/utils/http/HttpUtil.dart';
import 'package:codemode/utils/router/Routes.dart';
import 'package:codemode/utils/sp_util.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'AppModel.dart';
import 'constants/Constants.dart';
import 'models/sys_user_entity.dart';
import 'pages/home.dart';
import 'utils/router/NavigatorUtils.dart';

void main() {
  //初始化路由
  final router = new FluroRouter();
  Routes.configureRoutes(router);
  AppModel.router = router;
  SpUtil.getInstance();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: gethome(context),
    );
  }

  //判断是否登录
  Widget gethome(BuildContext context) {
    SysUserEntity userModelsEntity = new SysUserEntity();
    var userinfo = SpUtil.getString(Constants.USERINFO);

    if (userinfo.isNotEmpty) {
      var json = jsonDecode(userinfo);
      userModelsEntity = userModelsEntity.fromJson(json);
      AppModel.instance.usermodel = userModelsEntity;
      if (AppModel.instance.getUserModel != null) {
        return home();
      }
    }
    return MyHomePage(title: 'Flutter Demo Home Page');
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  TextEditingController phonecontroller = new TextEditingController();
  TextEditingController passworkcontroller = new TextEditingController();

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    AppModel.initScreen(context);
    return Scaffold(
      body: Stack(
        children: [
          Image.network(
            "https://daiyufile01.oss-cn-hangzhou.aliyuncs.com/23213.jpg",
            width: double.infinity,
            height: double.infinity,
            fit: BoxFit.cover,
          ),
          Center(
              child: Container(
            width: 500,
            height: 300,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: EdgeInsets.fromLTRB(0, 15, 0, 0),
                  child: Text(
                    "CodeHome",
                    style: TextStyle(color: Colors.black45, fontSize: 20),
                    textAlign: TextAlign.center,
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(25, 30, 25, 0),
                  child: Theme(
                      data: new ThemeData(
                          primaryColor: Colors.blue,
                          hintColor: Color(0xffA1A9B2)),
                      child: TextField(
                        controller: phonecontroller,
                        keyboardType: TextInputType.phone,
                        textInputAction: TextInputAction.next,
                        decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(10),
                            labelText: "账号",
                            hintText: "请输入注册的账号",
//                hintStyle: TextStyle(
//                    fontSize: ScreenUtil().setSp(20),
//                    color: Colors.red
//                ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(15.0),
//            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
                            ),
                            labelStyle:
                                TextStyle(fontSize: 20, color: Colors.blue)),
                        autofocus: false,
                      )),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(25, 15, 25, 0),
                  child: Theme(
                      data: new ThemeData(
                          primaryColor: Colors.blue,
                          hintColor: Color(0xffA1A9B2)),
                      child: TextField(
                        style: TextStyle(
                          fontSize: 25,
                          color: Colors.red,
                        ),
                        obscureText: true,
                        controller: passworkcontroller,
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.all(10),
                          labelText: "密码",
                          labelStyle:
                              TextStyle(fontSize: 20, color: Colors.blue),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(15.0),
//            borderSide: BorderSide(color: Colors.red, width: 3.0, style: BorderStyle.solid)//没什么卵效果
                          ),
                        ),
                        autofocus: false,
                      )),
                ),
                Expanded(
                    child: Center(
                  child: ButtonTheme(
                    minWidth: 300,
                    height: 60,
                    buttonColor: Colors.blueAccent,
                    child: RaisedButton(
                      textColor: Colors.white,
                      child: Text("登录"),
                      onPressed: _rqsustlogin,
                    ),
                  ),
                ))
              ],
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(15)),
            ),
          ))
        ],
      ),
    );
  }

  void _rqsustlogin() {
    if (phonecontroller.text.length <= 0) {
      Fluttertoast.showToast(msg: "请输入账号");
      return;
    }
    if (passworkcontroller.text.length <= 0) {
      Fluttertoast.showToast(msg: "请输入密碼");
      return;
    }

    this.login(phonecontroller.text, passworkcontroller.text);
  }

  void login(String name, String passwork) {
    MyLoadingDialog.showLoading(context, "登录中...", close: () {});
    Map<String, dynamic> data = {
      "username": name,
      "password": passwork,
    };
    HttpUtil().post(Constants.LOGIN_URL, data: data, success: (data) {
      SpUtil.putString(Constants.USERINFO, jsonEncode(data));
      MyLoadingDialog.hideLoading(context);
      print("~~~~~~~~" + SpUtil.getString(Constants.USERINFO));

      SysUserEntity userModelsEntity = new SysUserEntity();
      userModelsEntity = userModelsEntity.fromJson(data);
      AppModel.instance.usermodel = userModelsEntity;

      NavigatorUtils.push(context, Routes.HOME, clearStack: true);
    }, error: (errorstr) {
      MyLoadingDialog.hideLoading(context);
      Fluttertoast.showToast(msg: errorstr);
    });
  }
}
